package edu.ucla.cs.rpc.multicast.util;

import java.util.Comparator;

import edu.ucla.cs.rpc.multicast.network.message.Message;

/**
 * An instance of this class is used to implement the (ts(m), ms(m)) order
 * discussed in the DeFago paper. See the below classes for specific uses, and
 * references to the relevant sections of the papper.
 * 
 * @author Philip Russell Chase Covello
 * @see edu.ucla.cs.rpc.multicast.commhistory
 * @see edu.ucla.cs.rpc.multicast.destination.agreement
 * 
 */
public class IdentifierComparator implements Comparator<Message> {
	/**
	 * 
	 * @param m1 A message, to compare against the second argument.
	 * @param m2 A message, to compare against the first argument.
	 * @return A value indicating whether the first message is < or > the second
	 *         message. We assert that no two messgaes are equal.
	 */
	public int compare(Message m1, Message m2) {

		/* The final return value */
		int result = 1;

		if (m1.getTimestamp() < m2.getTimestamp()) {
			result = -1;
		} else if (m1.getTimestamp() == m2.getTimestamp()) {
			long sender1 = m1.getSenderID();
			long sender2 = m2.getSenderID();
			assert (sender1 != sender2); /* Require unique sender IDs */
			result = (sender1 < sender2 ? -1 : 1);
		}

		return result;
	}
}
